/*
 * 版权所有(c)  1952110078@qq.com  2022 - 2022
 */

package com.ldc.commonlibs.common;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.ldc.commonlibs.http.ApiConstant;
import com.ldc.commonlibs.http.NetCallback;
import com.ldc.commonlibs.http.RetrofitClient;

import java.lang.invoke.MutableCallSite;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Single;
import io.reactivex.rxjava3.core.SingleObserver;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.disposables.Disposable;

/**
 * @author liudc
 * @since 2022/7/3 13:49
 */
public abstract class ViewModelBase extends ViewModel {
    protected CompositeDisposable compositeDisposable;
    protected final String TAG = this.getClass().getCanonicalName();

    public ViewModelBase() {
        compositeDisposable = new CompositeDisposable();
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (compositeDisposable != null) {
            compositeDisposable.clear();
            compositeDisposable = null;
        }
    }


    protected <T> T getServer(String baseUrl, Class<T> clazz) {
        return RetrofitClient.getInstance().getService(baseUrl, clazz);
    }

    protected <T> T getServer(Class<T> clazz) {
        return getServer(ApiConstant.BASE_URL, clazz);
    }

    protected <T> void getNetDataSource(Single<T> dataSource, NetCallback<T> callback) {
        dataSource.compose(RxHelper.singleSchedulers())
                .subscribe(new SingleObserver<T>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onSuccess(@NonNull T t) {
                        if (callback != null) {
                            callback.onReceiver(t);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if (callback != null) {
                            callback.onBadReceiver(e);
                        }
                    }
                });

    }

}
